<?php

namespace app\common\model;

use app\admin\model\xshop\OrderProducts;
use think\Exception;
use think\Model;


class Ordersbk extends Model
{


    // 表名
    protected $name = 'orders';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    public $typeArr = [
        1 => '维修',
        2 => '安装',
        3 => '移机拆机',
        4 => '滤芯更换',
        5 => '商城订单',
    ];
    /*1 已接单 2已完成（结束）3，等待接单*/
    public $assignArr = [
        1 => '待出发',
        2 => '进行中',
        3 => '已完成',
        4 => '已取消',
    ];
    public $statuArr = [
        0 => '未支付',
        1 => '付成功',
        2 => '已取消',
        3 => '已完成',
    ];
    public $invoiceArr=[
        1 => '未申请',
        2 => '申请中',
        3 => '已完成',
    ];
    // 追加属性
    protected $append = [
        //'back_time_text',
        //'reserve_text',
        //'end_time_text',
        'paytime_text',
        //'type_text',
        'status_text',
        'assign_text',
        'get_time_text',
        //'photos_domain',
        'images_domain',
        'line_imgs_domain',
        'createtime_text',
        'invoice_text',
    ];


    public function getStepinfoAttr($value,$data){
        $value=isset($data['stepinfo'])?$data['stepinfo']:$value;
        return json_decode($value,true);
    }

    public function getImagesDomainAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['images']) ? $data['images'] : '');
        if (empty($value)) {
            return '';
        }
        $value = explode(',', $value);
        $arr = [];
        if (count($value) > 0) {
            foreach ($value as $item) {
                $arr[] = request()->domain() . $item;
            }
        }
        return $arr;
    }
    public function getLineImgsDomainAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['line_imgs']) ? $data['line_imgs'] : '');
        if (empty($value)) {
            return '';
        }
        $value = explode(',', $value);
        $arr = [];
        if (count($value) > 0) {
            foreach ($value as $item) {
                $arr[] = request()->domain() . $item;
            }
        }
        return $arr;
    }

    public function getAssignTextAttr($value, $data)
    {

        $value = $value ? $value : (isset($data['assign_status']) ? $data['assign_status'] : '');
        if( $data['paytype']== 'offline'&&$data['assign_status']==4){
           // $value=3;
        }
        return isset($this->assignArr[$value]) ? $this->assignArr[$value] : '暂无';
    }

    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['pay_status']) ? $data['pay_status'] : '');
        return isset($this->statuArr[$value]) ? $this->statuArr[$value] : '未支付';
    }
//    public function getEndTimeTextAttr($value, $data)
//    {
//        $value = $value ? $value : (isset($data['end_time']) ? $data['end_time'] : '');
//        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
//    }


    public function getPaytimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['paytime']) ? $data['paytime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }
    public function getCreatetimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['createtime']) ? $data['createtime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i", $value) : $value;
    }


    public function getinvoiceTextAttr($value, $data){
        $value = $value ? $value : (isset($data['has_invoice']) ? $data['has_invoice'] : '');
        return isset($this->invoiceArr[$value]) ? $this->invoiceArr[$value] : '未申请';
    }

    public function getGetTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['get_time']) ? $data['get_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setBackTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setEndTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setPaytimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setGetTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


    public function user()
    {
        return $this->belongsTo('User', 'uid', 'id', [], 'LEFT')->setEagerlyType(0);
    }
    public function custom()
    {
        return $this->belongsTo('User', 'uid', 'id', [], 'LEFT')->field('id,nickname,username,mobile');
    }


    /**
     * 获取支付信息
     * @$orderRow
     * pay_way 支付方式
     * pay_no 支付编号
     * title 订单名称
     * pay_price 支付金额
     */
    public function getPayinfo($orderRow)
    {
        //前往支付了
        $pay_type = isset($orderRow['pay_way']) ? $orderRow['pay_way'] : 'wechat';
        $domain = request()->domain();
        $notify = $domain . '/api/callback/notify/paytype/' . $pay_type;//异步回调地址
        $return = $domain . '/api/callback/returnx/paytype/' . $pay_type;//同步回调地址
        $params = [
            'amount' => $orderRow['pay_price'],
            'orderid' => $orderRow['pay_no'],
            'type' => $pay_type,
            'title' => $orderRow['title'],
            'notifyurl' => $notify,
            'returnurl' => $return,
            'method' => "miniapp",
            'openid' => $orderRow['openid'],
        ];
        try {
            $result = [];
            $payinfo = \addons\epay\library\Service::submitOrder($params);//微信扫码支付

            return is_array($payinfo) ? $payinfo : json_decode($payinfo, true);
        } catch (Exception $exception) {
            throw new \think\Exception($exception->getMessage(), 500);
        } catch (\Yansongda\Pay\Exceptions\Exception $exception) {
            throw new \think\Exception($exception->getMessage(), 500);
        }
        return $result;

    }

    public function orderNum($perfix = '')
    {
        $yearCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T');
        $year = date('Y');
        $number = $year . strtoupper(dechex(date('m'))) . date('d')
            . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
        return $perfix . $number;
    }

    public function searchList($map, $filed = "*",$per_page=14,$mapOr=[])
    {
        return $this->where($map)->whereOr($mapOr)
            ->with(['service','user','driver'])
            ->order("orders.id",'desc')
            //->field($filed)
            ->paginate($per_page)->each(function ($item){
                $item->hidden(['password', 'salt']);
                $item->getRelation('service')->visible(['service_name','mobile','avatar']);
                $item->getRelation('user')->visible(['nickname','mobile','avatar']);
                $item->getRelation('driver')->visible(['nickname','mobile','avatar']);
                if($item['cancel_reason']=='已完结(收款码)'){
                    $item['cancel_reason']='已完成';
                }
            });
    }

//    public function products()
//    {
//        return $this->hasOne(OrderProducts::class, 'order_id', 'id')->field('order_id,title,image,skuinfo,productinfo,attributes,title');
//    }

//    public function getImageDomainAttr($value, $data)
//    {
//        $value = isset($data['image']) ? $data['image'] : null;
//        if (!empty($value)) {
//            $domain = \request()->domain();
//            return $domain . $data['image'];
//        }
//        return '';
//    }
    public function driver()
    {
        return $this->belongsTo('User', 'driver_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
    public function cars()
    {
        return $this->belongsTo(Cards::class, 'car_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function service(){
        return $this->belongsTo(User::class, 'service_id', 'id')->setEagerlyType(0);
    }
    public function initStepinfo(){
        return
            [
                ['step'=>1,'name'=>'用户下单','date'=>''],
                ['step'=>2,'name'=>'司机出发','date'=>''],
                ['step'=>3,'name'=>'生成支付订单','date'=>''],
                ['step'=>4,'name'=>'订单完成','date'=>'']
            ];
    }

    public function orderNums($uid,$filed='uid'){
        $delivered=$this->where(['assign_status'=>1,$filed=>$uid])->count('id');
        $progress=$this->where(['assign_status'=>2,$filed=>$uid])->count('id');
        $overed=$this->where(['assign_status'=>3,$filed=>$uid])->count('id');
        $cancel=$this->where(['assign_status'=>4,$filed=>$uid])->count('id');
       return [
            'delivered'=>['value'=>$delivered,'name'=>'待派送'],
            'progress'=>['value'=>$progress,'name'=>'进行中'],
            'overed'=>['value'=>$overed,'name'=>'已完成'],
            'cancel'=>['value'=>$cancel,'name'=>'已取消']
        ];
    }
}
